package com.atguigu.yuntai.lineage.service.impl;

import com.atguigu.yuntai.lineage.bean.Insert;

import com.atguigu.yuntai.lineage.parser.SqlParser;
import com.atguigu.yuntai.lineage.service.LineageService;
import com.atguigu.yuntai.lineage.service.Neor4jService;
import com.atguigu.yuntai.schedule.service.TDsTaskDefinitionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.hadoop.hive.ql.parse.ParseException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LineageServiceImpl implements LineageService {


    @Autowired(required=true)
    TDsTaskDefinitionService tDsTaskDefinitionService;

    @Autowired
    Neor4jService neor4jService;

    public void syncTaskSqlToNeo4j(){


        List<String> taskSql = tDsTaskDefinitionService.getAllTaskSql();

        List<Insert> insertList = getInsertList(taskSql);

        neor4jService.saveInsertList(insertList);

    }





    private static List<Insert>  getInsertList(List<String> sqlList){

        SqlParser sqlParser = new SqlParser();
        List<Insert> insertList = new ArrayList<>();
        for (String sql : sqlList) {
            try {
                sqlParser.getLineageInfo(sql);
            } catch (ParseException e) {
                System.out.println("错误sql :"+sql);
                e.printStackTrace();
                throw new RuntimeException("sql解析失败");
            } catch (SemanticException e) {
                e.printStackTrace();
                throw new RuntimeException("sql语法错误");
            }

            TreeSet inputTableSet = sqlParser.getInputTableSet();
            TreeSet outputTableSet = sqlParser.getOutputTableSet();
            String outputTableName="";
            String inputTableName="";
            for (Object o : outputTableSet) {
                outputTableName = (String) o;
            }
            for (Object o : inputTableSet) {
                inputTableName = (String) o;
                if(checkValidTable(inputTableName)) continue;
                insertList.add( new Insert(inputTableName,outputTableName)) ;
            }
        }
        return insertList;
    }

    private static boolean  checkValidTable(String tableName){
        if(tableName.indexOf(".")>=0){ //不含库名的认定为临时表
            return  false;
        }
        return true;
    }




}
